import React, { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Button, NavBar, SafeArea } from "antd-mobile";
import { PortingContainer } from "./PortingContainer";
import { connect, getState } from "../../store";
import { mapTreeData } from "../../utils";
import { chatroom_create, chatroom_adduser } from "../../apis";
import type { MapTreeDataResult, Key } from "../VirtualScroll";
import type { SimpleUser } from "../../apis";
import { Avatar } from "../Avatar";

export interface CreatorProps {
  userMap: Map<string | number, SimpleUser>;
  loginUser: SimpleUser;
  setVisible: React.Dispatch<React.SetStateAction<boolean>>;
  title?: React.ReactNode | ((items: Key[]) => React.ReactNode);
  multiple?: boolean;
  removeCurrent?: boolean;
  filter?: (user?: SimpleUser) => boolean;
  value?: Key | Key[];
  onChange?: (value?: Key | Key[]) => void;
  chatroom_id?: string;
  members?: string[];
  /** 点击确定回调 */
  onOk?: () => void;
}

function _Creator(props: CreatorProps) {
  const { userMap, loginUser, setVisible, title, multiple, removeCurrent, filter, value, onChange, chatroom_id, members, onOk } = props;
  const { username, name: currentName } = loginUser || {};
  const navigate = useNavigate();

  const userData = useMemo<MapTreeDataResult<Key, SimpleUser>>(() => {
    return mapTreeData(
      [...userMap.entries()]
        .filter(([k, u]) => {
          if (typeof k === "number") {
            return false;
          }
          if (removeCurrent && u.username === username) {
            return false;
          }
          return !filter || filter(u);
        })
        .map(([, user]) => {
          const dept = user.group || "";
          const desc = <small style={{ opacity: 0.7 }}>({[user.username, user.group].filter((n) => !!n).join(" | ")})</small>;
          let disabled = {};
          if (members && members.includes(user.username)) {
            disabled = { disabled: true };
          }
          return {
            ...user,
            label: `${user.name}-${user.username}-${dept}`,
            desc,
            ...disabled,
            title: <>
              <Avatar src={user.avatar} style={{ '--size': '28px', float: 'left', margin: '12px 8px 0 -12px' }}/> {user.name}
            </>
          };
        }),
      {
        key: "username",
        value: "username",
        title: "title",
        label: "label",
        __with_pinyin__: true,
        __with_rest__: true,
      }
    );
  }, [userMap, value, members]);

  const [items, selectItems] = useState<Key[]>([].concat(props.value || members || []));
  const [showSelected, setShowSelected] = useState(false);

  function handleCreate(members: string[]) {
    const memberNameArray = members.map((member) => userMap.get(member).name).concat([currentName]);

    let chatroomName = memberNameArray?.join("、") as string;
    chatroomName = chatroomName?.length > 15 ? chatroomName.slice(0, 15) + "..." : chatroomName;

    chatroom_create({
      name: chatroomName,
      users: [
        ...members.map((username) => ({ username })),
        {
          username,
          is_master: true,
        },
      ],
    }).then((res) => {
      if (res?.success && res?.data?._id) {
        navigate(`/chat_page/${res?.data?._id}`);
      }
    });
  }

  async function handleAddMembers(members: string[]) {
    await chatroom_adduser({ _id: chatroom_id, users: [...members.map((username) => ({ username }))] });
  }

  return (
    <>
      <SafeArea position="top" />
      <NavBar
        onBack={() => {
          setVisible(false);
          selectItems([].concat(props.value || []));
        }}
        right={
          <>
            <Button
              size="small"
              fill="none"
              color="warning"
              onClick={() => {
                selectItems([]);
              }}
            >
              清空
            </Button>
            <Button
              size="small"
              fill="none"
              color="primary"
              onClick={async () => {
                onChange && onChange(props.multiple ? items : items[0]);
                if (chatroom_id) {
                  await handleAddMembers(items as string[]);
                } else {
                  handleCreate(items as string[]);
                }
                onOk?.();
                setVisible(false);
              }}
            >
              确定
            </Button>
          </>
        }
      >
        <span onClick={() => setShowSelected(!showSelected)}>{typeof title === "function" ? title(items) : title}</span>
      </NavBar>
      <PortingContainer
        treeData={userData}
        value={items}
        onChange={(v) => {
          const items = v ? [].concat(v) : [];
          selectItems(items);
        }}
        showCheckedOnly={showSelected}
        multiple={multiple}
      />
    </>
  );
}

const Creator = connect(() => {
  const { loginUser, userMap } = getState();
  return { loginUser, userMap };
})(_Creator);

export default Creator;
